// 引入接口文件
import {
    getDetail,
    update,
    create,
    queryAllAddress,
    getRegion,
    getMerchant,
    getMerchandise
  } from './integralManagementDetailServ.js'
  import Cookie from 'js-cookie'
  // 导入项目全局配置文件
import config from 'config/config'
  // 对象和JSON字符串互转
  import { parse } from 'qs'
  // 弹出消息框
  import { message } from 'antd'
  // 日期处理对象
  import moment from 'moment'
  /*isEmpty 对象是否为空
   *isArray 对象是否数组
   *cloneDeep 对象深拷贝
   */
  import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
  // 引入路由对象
  import { hashHistory } from 'dva/router'
  import AppBus from 'utils/bus'
  import { makeAddress } from "utils/util"

  // 初始默认状态
const defultState = {
    id:'',
    loading: false,
    btnLoading: false,
    medias:[],
    pageType: '',
    isClone:false,
    regionList:[],
    areaList: [],//省市区列表
    selectAddressList:[],//选中的项目地址列表
    merchantList: [],//商家
    merchandiseList: [], //商品类型
    formData: {
        "giftName":'',
        "giftJj":'',
        "regionId":'',
        "regionName":'',
        "issj":'',
        "imgUrl":"",
        "integral":0,
        "sumLimit":0,
        "isPost":"",
        "remark":"",
        "jfGiftBList":[],
        jfMerchantId: '',//商家id
        jfMerchandiseId:'',//商品类别id
        jfMerchantName:'',//商家名称
        jfMerchandiseName:'',//商品类别名称
        isUnion: '',//是否商家联盟//0否1是
        "stock": null
    },
}

// 声明module
const tmpModule = {
    // namespace: 'secondKillingSetting',
    // 默认状态
    state: cloneDeep(defultState),
    // 入口函数(先执行)
    subscriptions: {
      setup({ dispatch, history }) {
        history.listen(({ pathname, query }) => {
          // 页面路由匹配时执行
          if ('' + tmpModule.pathname === '' + pathname) {
            dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
            dispatch({ type:'getAreaList', payload: {} });
            dispatch({type:'getRegion',payload:{}});
            dispatch({type:'getMerchant',payload:{}});
            dispatch({type:'getMerchandise',payload:{}});
            if (query.pageType == 'edit' || query.pageType == 'detail') {
              dispatch({
                type: 'updateStore',
                payload: {
                  pageType: query.pageType,
                  id: query.id,
                  isClone: query.isClone||false,
                }
              })
              dispatch({
                type:'getDetail',
                payload:{
                  id:query.id
                }
              })
            } else {
              dispatch({
                type: 'updateStore',
                payload: {
                  pageType: query.pageType,
                  id: query.id,
                  isClone: query.isClone||false,
                }
              })
            }
          } // end if
        }) // end listen
      },
    },
  
    // 方法列表
    effects: {
      // 查询记录  详情

      //获取详情
  
      // 修改
      *update({ payload }, { put, select, call }) {
        try{
          let {formData, medias,selectAddressList} = yield select(state => state[tmpModule.namespace]);
          for(let item in formData){
            if("id,giftName,giftJj,regionId,regionName,issj,imgUrl,integral,sumLimit,isPost,remark,jfGiftBList,jfMerchantId,jfMerchandiseId,jfMerchantName,jfMerchandiseName,isUnion,stock".indexOf(item) == -1){
              delete formData[item];
            }
          };
          if(medias.length > 0){
            formData.imgUrl = "";
            medias.map((item,idx)=>{
              if(idx > 0){
                formData.imgUrl += ",";
              }
              formData.imgUrl += item;
            });
          }
          if(selectAddressList.length > 0){
            formData.jfGiftBList = [];
            selectAddressList.map((item,idx)=>{
              let p = {
                projectAddr:item.mapAddress,
                projectname:item.productName,
                projectid:item.productId
              }
              formData.jfGiftBList.push(p);
            });
          }
          formData.stock = parseInt(formData.stock)
          const userName = Cookie.get(config.cookie.userName);
          formData.updatePerson = userName;
          const { success, msg } = yield call(update, { ...formData })
          if(success){
            message.success('编辑成功');
            hashHistory.push('/home/integralMall/integralManagement')
            yield put({ type: 'updateStore',payload:{btnLoading:false}})
          }else{
            message.error(msg);
          }
        }catch(e){
          console.log(e)
        }
      },
      // 新增
      *create({ payload }, { put, select, call }) {
        try{
          let {formData, medias,selectAddressList} = yield select(state => state[tmpModule.namespace])
          if(medias.length > 0){
            formData.imgUrl = "";
            medias.map((item,idx)=>{
              if(idx > 0){
                formData.imgUrl += ",";
              }
              formData.imgUrl += item;
            });
          }
          if(selectAddressList.length > 0){
            formData.jfGiftBList = [];
            selectAddressList.map((item,idx)=>{
              let p = {
                projectAddr:item.mapAddress,
                projectname:item.productName,
                projectid:item.productId
              }
              formData.jfGiftBList.push(p);
            });
          }
          formData.stock = parseInt(formData.stock)
          const userName = Cookie.get(config.cookie.userName);
          formData.creator = userName;
          const { success, msg } = yield call(create, { ...formData })
          if(success){
            message.success('新增成功');
            hashHistory.push('/home/integralMall/integralManagement')
            yield put({ type: 'updateStore',payload:{btnLoading:false}})
          }else{
            message.error(msg);
          }
        }catch(e){
          console.log(e)
        }
      },
      *getRegion({ payload }, { put, call, select }) {
        try {
          let {success,rows} = yield call(getRegion, {...payload.params })
          if (success) {
            let regionList = rows
              regionList.forEach((item,index)=>{
                        item.value = item.regionId
                        item.label = item.regionName
                        item.key = index
              })
            yield put({ type: 'updateStore', payload: { regionList } })
          }
        } catch (e) {
        }
      },
      *getMerchant({ payload }, { put, call, select }) {
          let {merchantList} = yield select(state => state[tmpModule.namespace])
          let params = {uid:localStorage.getItem("username"),regionId:Cookie.get(config.cookie.regionId)}
          let {success,rows} = yield call(getMerchant, params)
          if (success) {
            let list = rows
            merchantList = list.map((item,index)=>{
                  return {
                    label: item.name,
                    value: item.id,
                    key: index
                  }
              })
            yield put({ type: 'updateStore', payload: { merchantList } })
          }
      },
      *getMerchandise({ payload }, { put, call, select }) {
          let {merchandiseList} = yield select(state => state[tmpModule.namespace])
          let params = {uid:localStorage.getItem("username"),regionId:Cookie.get(config.cookie.regionId)}
          let {success,rows} = yield call(getMerchandise, params)
          if (success) {
            let list = rows
            merchandiseList = list.map((item,index)=>{
                  return {
                    label: item.typeName,
                    value: item.id,
                    key: index
                  }
              })
            yield put({ type: 'updateStore', payload: { merchandiseList } })
          }
      },
      *getDetail({payload},{put,call,select}){
        let {medias,selectAddressList} = yield select(state => state[tmpModule.namespace])
       try{
        let {data,success}=yield call(getDetail,payload)
        if(success){
          if(data.imgUrl && data.imgUrl != ""){
              medias = data.imgUrl.split(",");
          }
          if(data.jfGiftBList && data.jfGiftBList.length > 0){
            data.jfGiftBList.map((item,idx)=>{
              let p = {
                mapAddress:item.projectAddr,
                productName:item.projectname,
                productId:item.projectid,
              };
              selectAddressList.push(p);
            });
          }
          yield put({
            type:'updateStore',
            payload:{
              formData:data,
              medias,
              selectAddressList
            }
          })
        }
       }catch(err){
  
       }
        
      },
      *getAreaList({ payload }, { put, call, select }) {
          try {
              const { success, data } = yield call(queryAllAddress, {})
              if (success) {
                  //todo: 接口格式调整后删除
                  let areaList = []
                  let arr = [data[0]]
                  let attr = [data[data.length - 1]]
                  data[0] = {
                      label: "北京",
                      value: "110100",
                      children: arr
                  }
                  data[data.length - 1] = {
                      label: "澳门",
                      value: "820000",
                      children: attr
                  }
                  //console.log(data,"data")
                  //去掉第三级，
                  areaList = makeAddress(data, 2, false)
                  yield put({ type: 'updateStore', payload: { areaList:areaList} })
              }
          } catch (e) {
          }
      },
    },
    // 存入状态机
    reducers: {
      updateStore(preState, action) {
        return Object.assign({}, preState, action.payload)
      },
    }
  }
  
  export default tmpModule